/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.wfaces.mb;

import com.wfaces.dao.Dao;
import com.wfaces.entities.Discussion;
import com.wfaces.entities.User;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.persistence.NoResultException;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.primefaces.event.TabChangeEvent;

/**
 *
 * @author lhoussin
 */
@ManagedBean
@SessionScoped
public class ChatMB implements Serializable {

    private static final Logger logger = Logger.getLogger(ChatMB.class.getName());
    private static final long serialVersionUID = 1L;
    private User connectedUser = new User();
    private String message;
    boolean connectionEstablished = false;
    private List<Discussion> discussions;
    @ManagedProperty(value = "#{searchMB}")
    SearchMB searchMB;
    private User advUser;

    /**
     * Creates a new instance of chatMB
     */
    public ChatMB() {
        logger.info("Début du traitement! !");
        discussions = new ArrayList<Discussion>();
    }

    public void select(User u) {
        this.advUser = u;
        logger.info("Selected User = " + u);
        searchMB.getSelectedUsers().remove(u);
        searchMB.getSelectedUsers().add(0, u);
    }

    public void change(TabChangeEvent event) {
        logger.info("changing tab to user");
        String title = event.getTab().getTitle().trim();
        logger.info("Title of tab is " + title);
        try {
            advUser = (User) Dao.find(User.class, Long.parseLong(title));
        } catch (NumberFormatException e) {
            return;
        }

        logger.info("advUser = " + advUser.getId());
        if (connectedUser == null || advUser == null) {
            logger.info("connectedUser ou advUser NULL");
            logger.info("ADVUSER = " + advUser);
            logger.info("ConUSER = " + connectedUser);
            discussions = new ArrayList<Discussion>();
        }

        discussions = Dao.findDiscussionByUsers(connectedUser, advUser, 0, 10);
    }

    public void send() {
        logger.info("Conn user = " + connectedUser);
        logger.info("Adv User = " + advUser);
        Discussion d = new Discussion();
        d.setDt(Calendar.getInstance().getTime());
        d.setToGroupe(null);
        d.setId(null);
        d.setMessage(message);
        d.setToUser(advUser);
        d.setUser(connectedUser);
        logger.info("Disc.Msg = " + d.getMessage());
        try {
            Dao.begin();
            Dao.create(d);
            Dao.commit();
            discussions.add(d);
        } catch (Exception e) {
            logger.info("Exception :", e);
        }
        message = "";
    }

    public String login() {
        try {
            connectedUser = Dao.findUserByLoginAndPassword(connectedUser.getLogin(), connectedUser.getPassword());
            logger.info("Con Usr tof = " + connectedUser.getTof());
        } catch (NoResultException nresex) {
            connectedUser = null;
        }
        logger.info(connectedUser);
        if (connectedUser != null) {
            return "users";
        } else {
            return "index";
        }
    }

    @SuppressWarnings("unchecked")
    public List<User> getUsers() {

        searchMB.getSelectedUsers().remove(connectedUser);

        if (advUser == null) {
            advUser = searchMB.getSelectedUsers().size() > 0 ? searchMB.getSelectedUsers().get(0) : null;
        }

        ArrayList<User> first8Users = new ArrayList<User>();

        for (int i = 0; i < ((searchMB.getSelectedUsers().size() >= 8) ? 8 : searchMB.getSelectedUsers().size()); i++) {
            first8Users.add(searchMB.getSelectedUsers().get(i));
        }
        return first8Users;
    }

    public List< User> getAllUsers() {
        //Collections.reverse(searchMB.getSelectedUsers());
        return searchMB.getSelectedUsers();
    }

//    public List<User> getOtherUsers() {
//        ArrayList otherUsers = new ArrayList();
//        for (int i = 10; i < ((users.size() >= 10) ? users.size() : 9); i++) {
//            otherUsers.add(users.get(i));
//        }
//        return otherUsers;
//    }
    
    public boolean isConnectionEstablished() {
        return connectionEstablished;
    }

    public void setConnectionEstablished(boolean connectionEstablished) {
        this.connectionEstablished = connectionEstablished;
    }

    public List<Discussion> getDiscussions() {
        discussions = Dao.findDiscussionByUsers(connectedUser, advUser, 0, 0);
        java.util.Collections.reverse(discussions);
//        for (int i = 1; i < discussions.size(); i++) {
//            Discussion discussion = discussions.get(i);
//            if (discussions.get(i - 1).getUser().getId() == discussion.getUser().getId()) {
//                discussions.get(i - 1).setMessage(discussions.get(i - 1).getMessage() + "\n" + discussion.getMessage());
//                if (discussions.remove(discussion)) {
//                    i--;
//                }
//            }
//            System.out.println("message = " + discussions.get(i).getMessage());
//        }

        return discussions;
    }

    public void setDiscussions(List<Discussion> discussions) {
        this.discussions = discussions;
    }

    public User getConnectedUser() {
        return connectedUser;
    }

    public void setConnectedUser(User connectedUser) {
        this.connectedUser = connectedUser;
    }

    public User getAdvUser() {
        return advUser;
    }

    public void setAdvUser(User advUser) {
        logger.info("AdvUser setted by changing tab advuser.id = " + advUser);
        this.advUser = advUser;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String startChating(List<User> users) {
        return "chat";
    }

    public String logout() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        HttpSession httpSession = (HttpSession) facesContext.getExternalContext().getSession(false);
        httpSession.invalidate();
        return "index?faces-redirect=true";
    }

    public SearchMB getSearchMB() {
        return searchMB;
    }

    public void setSearchMB(SearchMB searchMB) {
        this.searchMB = searchMB;
    }
//    public void setUsers(List<User> users) {
//        this.users = users;
//    }
}